package gw.demo2.service;

import gw.demo2.entity.Merchant;
import gw.demo2.entity.Product;
import gw.demo2.entity.PurchaseRecord;
import gw.demo2.mapper.MerchantMapper;
import gw.demo2.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import gw.demo2.mapper.PurchaseRecordMapper;

import java.util.List;

@Service
public class MerchantService {
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private PurchaseRecordMapper purchaseRecordMapper;

    public Merchant login(int merchantId, String password) {
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        if (merchant != null && merchant.getPassword().equals(password)) {
            return merchant;
        }
        return null;
    }

    public boolean register(String nickname, String password) {
        if (merchantMapper.selectMerchantByNickname(nickname) != null) {
            return false;
        }
        Merchant merchant = new Merchant();
        merchant.setNickname(nickname);
        merchant.setPassword(password);
        return merchantMapper.insertMerchant(merchant) > 0;
    }

    public int getMerchantIdByNickname(String nickname) {
        return merchantMapper.selectMerchantByNickname(nickname).getMerchantId();
    }

    public boolean updateMerchantInfo(int merchantId, String newNickname, String newPassword) {
        Merchant merchant = new Merchant();
        merchant.setMerchantId(merchantId);
        merchant.setNickname(newNickname);
        merchant.setPassword(newPassword);
        return merchantMapper.updateMerchant(merchant) > 0;
    }

    public boolean addProduct(Product product) {
        return productMapper.insertProduct(product) > 0;
    }
    public Merchant selectMerchantById(int merchantId) {
        return merchantMapper.selectMerchantById(merchantId);
    }
    public List<Product> getProductsByMerchantId(int merchantId) {
        return merchantMapper.selectProductsByMerchantId(merchantId);
    }

    public List<PurchaseRecord> getPurchaseRecordsByMerchantId(int merchantId) {
        return purchaseRecordMapper.selectPurchaseRecordsByMerchantId(merchantId);
    }
}